package com.wpml.netty.rpc.server;

import com.wpml.netty.rpc.common.MyBody;
import com.wpml.netty.rpc.common.MyHeader;
import com.wpml.netty.rpc.common.PackMsg;
import com.wpml.netty.rpc.util.SerDerUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @Description
 * @Date 2021-05-06
 * @Author wangpei
 **/
public class ServerDecode extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf buf, List<Object> out) throws Exception {
        while (buf.readableBytes() >= 104) {
            byte[] bytes = new byte[104];
            // 读数据单不移动指针
            buf.getBytes(buf.readerIndex(), bytes);
            MyHeader header = (MyHeader) SerDerUtil.deSer(bytes);

            if (buf.readableBytes() - 104 >= header.getDataLen()) {
                //移动指针到body开始的位置
                buf.readBytes(104);
                byte[] data = new byte[(int) header.getDataLen()];
                buf.readBytes(data);
                if (header.getFlag() == 0x14141414) {
                    MyBody body = (MyBody) SerDerUtil.deSer(data);
                    out.add(new PackMsg(header, body));
                }
                if (header.getFlag() == 0x14141424) {
                    MyBody body = (MyBody) SerDerUtil.deSer(data);
                    out.add(new PackMsg(header, body));
                }
            } else {
                break;
            }
        }
    }
}
